本篇之克里克絕非克里克,但欲找華生,誠請參閱隔壁麻瓜的程式翻譯書之華生。
圖片來源:我
沒什麼就只是想讓你看看我的鼠
本篇續紀錄鼠輩之不可思議事件:click。
此事件應為鼠輩最常發生之事件,於點按且放開鼠輩發生。會因介面環境設定而有所不同,例如點按且放開鼠輩之時間差。
規範原文:
The click event type MUST be dispatched on the topmost event target indicated by the pointer, when the user presses down and releases the primary pointer button, .... The actuation method of the mouse button depends upon ... the environment configuration, e.g., it MAY depend on ... the delay between the press and release of the pointing device button.
另,只有鼠輩之主要點按處可以觸發click事件,可由事件之button或buttons屬性判斷當前點按處為何(關於事件之button或buttons屬性將於後篇進一步紀錄詳細)。
若要觀測鼠輩之非主要點按處之事件,則可觀察auxclick事件之發生。
規範原文:
The click event should only be fired for the primary pointer button (i.e., when button value is 0, buttons value is 1). Secondary buttons (like the middle or right button on a standard mouse) MUST NOT fire click events. See auxclick for a corresponding event that is associated with the non-primary buttons.
以下示例為鼠之宅建造一電流切換裝置。
const switchBar = document.querySelector(".switch");
function changeLight(event) {
document.body.classList.toggle("night");
}
switchBar.addEventListener("click", changeLight);
分段註釋如下:
選取電流切換裝置元素。
小註:元素變數名稱無法使用switch保留文字,因此命為switchBar
const switchBar = document.querySelector(".switch");
定義函式之術名changeLight,內容為將body添一class屬性之內容night,用以控制其他元素之樣式。若body之class屬性已有night,則清除night以復原至初始樣式。
function changeLight(event) {
document.body.classList.toggle("night");
}
對電流切換裝置元素設定事件觀測器以觀測click事件,並施以changeLight函式之術。
switchBar.addEventListener("click", changeLight);
鼠輩點按並放開電流切換裝置,可使鼠之宅切換白日與黑夜模式,亦可喚醒夜行性之鼠。
click事件與其他不可思議事件之糾葛click事件並非必由鼠輩觸發。查閱keydown事件之規範可知,若元素於受矚之狀態下施力於Enter或Space鍵石,則其預設將觸發click事件。
規範原文:
If the key is the Enter or Space key and the current focus is on a state-changing element, the default action MUST be to dispatch a click event
以下示例挪用先前篇章之術式並加以改造,使其能顯示已按壓過之鍵石。
const button = document.querySelector("button");
const downKeys = document.querySelector(".keys.down");
function showPressedKeys(event, keys, direction) {
const key = event.key;
keys.innerHTML += `<div class="key-${direction}">${key}</div>`;
}
function myFunction() {
alert("打咩");
}
button.addEventListener("click", myFunction);
window.addEventListener("keydown", (event) => {
showPressedKeys(event, downKeys, "down");
});
將事件觀測器設於按鈕元素,並觀測click事件之觸發,用以彈跳出「打咩」視窗。
button.addEventListener("click", myFunction);
首先按壓Tab鍵石使按鈕元素處於受矚之狀態,續按壓Enter鍵石後,觸發了click事件之函式之術。可證實click事件亦可不藉鼠輩之力發生。
click事件可能晚於mousedown及mouseup事件發生之時。
規範原文:
The click event MAY be preceded by the mousedown and mouseup events on the same element, ...
以下簡單示例將三事件之事件觀測器設定於電流切換裝置,並於操術板印出當前觸發之事件。
switchBar.addEventListener("click", (event) => {
console.log(event.type);
});
switchBar.addEventListener("mousedown", (event) => {
console.log(event.type);
});
switchBar.addEventListener("mouseup", (event) => {
console.log(event.type);
});
可觀察操術板顯示事件觸發順序為:mousedown → mouseup → click

https://github.com/CReticulata/2024ithome/tree/main/Day11
鼠輩:滑鼠
點按處:按鍵
主要點按處:primary pointer button
操術板:開發者工具